package com.kexilo.system.user.controller;


import com.kexilo.core.common.annotation.Debounce;
import com.kexilo.core.common.annotation.Idempotent;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.core.domain.TreeSelect;
import com.kexilo.core.common.core.page.TableDataInfo;
import com.kexilo.core.common.core.web.BaseController;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.enums.BusinessType;
import com.kexilo.core.common.utils.ExcelUtil;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.role.domain.SysRole;
import com.kexilo.core.user.domain.SysUser;
import com.kexilo.system.user.service.ISysRoleService;
import com.kexilo.system.user.service.ISysUserService;
import jakarta.servlet.http.HttpServletResponse;
import io.swagger.v3.oas.annotations.Operation;

import java.util.Arrays;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author Kexilo
 */
@RestController
@RequestMapping("/system/user")
@Tag(name = "用户管理", description = "用户信息管理相关接口")
public class SysUserController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    @Operation(summary = "获取用户列表", description = "分页获取用户列表信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Debounce(interval = 10, message = "导出操作过于频繁，请稍后再试")
    @PostMapping("/export")
    @Operation(summary = "导出用户列表", description = "导出用户列表数据")
    public void export(SysUser user, HttpServletResponse response) {
        try {
            List<SysUser> list = userService.selectUserList(user);
            ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
            util.exportExcel(list, "用户数据", response);
        } catch (Exception e) {
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }

    /**
     * 导入用户数据
     */
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @Debounce(interval = 30, message = "导入操作过于频繁，请稍后再试")
    @Idempotent(timeout = 10, message = "请勿重复导入相同文件")
    @PostMapping("/importData")
    @Operation(summary = "导入用户数据", description = "批量导入用户数据")
    public R<String> importData(MultipartFile file, boolean updateSupport) throws Exception {
        try {
            if (file == null || file.isEmpty()) {
                return R.fail("导入文件不能为空");
            }
            
            ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
            List<SysUser> userList = util.importExcel(file.getInputStream());
            
            if (userList.isEmpty()) {
                return R.fail("导入数据为空");
            }
            
            String operName = SecurityUtils.getUsername();
            String message = userService.importUser(userList, updateSupport, operName);
            
            return R.success(message);
            
        } catch (Exception e) {
            return R.fail("导入失败: " + e.getMessage());
        }
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    @Operation(summary = "获取导入模板", description = "下载用户导入模板")
    public void importTemplate(HttpServletResponse response) {
        try {
            // 创建模板数据（空数据，只有表头）
            List<SysUser> templateList = new ArrayList<>();
            
            ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
            util.exportExcel(templateList, "用户数据导入模板", response);
            
        } catch (Exception e) {
            throw new RuntimeException("模板下载失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public R<SysUser> getInfo(@Parameter(description = "用户ID") @PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        SysUser user = userService.selectUserById(userId);
        return success(user);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "请勿重复提交用户信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#user.username", timeout = 5, message = "该用户名正在处理中，请稍后再试")
    @PostMapping
    @Operation(summary = "新增用户", description = "新增用户信息")
    public R<Void> add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 3, message = "请勿频繁修改用户信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#user.userId + ':' + #user.updateTime", timeout = 3, message = "用户信息正在更新中，请稍后再试")
    @PutMapping
    @Operation(summary = "修改用户", description = "修改用户信息")
    public R<Void> edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUsername() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 5, message = "删除操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, timeout = 5, delKey = true, message = "删除操作正在进行中，请勿重复操作")
    @DeleteMapping("/{userIds}")
    @Operation(summary = "删除用户", description = "批量删除用户")
    public R<Void> remove(@Parameter(description = "用户ID数组") @PathVariable Long[] userIds) {
        if (Arrays.asList(userIds).contains(SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 10, message = "密码重置操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#user.userId", timeout = 5, message = "该用户密码正在重置中，请稍后再试")
    @PutMapping("/resetPwd")
    @Operation(summary = "重置密码", description = "重置用户密码")
    public R<Void> resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    @Operation(summary = "修改用户状态", description = "启用/停用用户")
    public R<Void> changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    @Operation(summary = "获取用户授权角色", description = "获取用户的授权角色信息")
    public R<Object> authRole(@Parameter(description = "用户ID") @PathVariable("userId") Long userId) {
        SysUser user = userService.selectUserById(userId);
        try {
            List<SysRole> roles = roleService.selectRolesByUserId(userId);
            Map<String, Object> result = new HashMap<>();
            result.put("roles", roles);
            result.put("total", roles.size());
            return R.success(result);
        } catch (Exception e) {
            return R.fail("获取用户角色失败: " + e.getMessage());
        }
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "角色分配操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#userId", timeout = 3, message = "该用户角色正在分配中，请稍后再试")
    @PutMapping("/authRole")
    @Operation(summary = "用户授权角色", description = "为用户分配角色")
    public R<Void> insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    @Operation(summary = "获取部门树", description = "获取部门树形结构数据")
    public R<Object> deptTree(SysUser user) {
        try {
            // 这里应该调用部门服务获取部门树
            // List<SysDept> depts = deptService.selectDeptList(new SysDept());
            // List<TreeSelect> deptTree = deptService.buildDeptTreeSelect(depts);
            
            // 临时返回空的树结构
            List<TreeSelect> deptTree = new ArrayList<>();
            
            Map<String, Object> result = new HashMap<>();
            result.put("deptTree", deptTree);
            result.put("message", "部门树获取成功（当前为空数据，需集成部门服务）");
            
            return R.success(result);
        } catch (Exception e) {
            return R.fail("获取部门树失败: " + e.getMessage());
        }
    }
}
